package com.quanxiaoha.weblog.admin.service.Impl;

import com.quanxiaoha.weblog.admin.model.vo.user.GetUserInfoRspVO;
import com.quanxiaoha.weblog.admin.model.vo.user.UpdateAdminUserPasswordReqVO;
import com.quanxiaoha.weblog.admin.service.AdminUserService;
import com.quanxiaoha.weblog.common.domain.mapper.UserMapper;
import com.quanxiaoha.weblog.common.enums.ResponseCodeEnum;
import com.quanxiaoha.weblog.common.utils.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class AdminUserServiceImpl implements AdminUserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserMapper userMapper;


    @Override
    public Response updatePassword(UpdateAdminUserPasswordReqVO updateAdminUserPasswordReqVO) {
        //获取用户名以及密码
        String username = updateAdminUserPasswordReqVO.getUsername();
        String password = updateAdminUserPasswordReqVO.getPassword();

        //将密码用passwordEcoder加密
        String encodePassword = passwordEncoder.encode(password);

        //根据传入用户名以及加密后的密码更新到数据库
        int i = userMapper.updatePasswordByUsername(username, encodePassword);

        return i == 1 ? Response.success() : Response.fail(ResponseCodeEnum.USERNAME_NOT_FOUND);
    }

    @Override
    public Response getUserName() {
        //根据ThreadLocal获取当前用户姓名用于查询回显
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();

        //将用户名封装后返回
        return Response.success(GetUserInfoRspVO.builder().username(username).build());
    }
}
